package com.shinhye.elephantsafe.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

import com.shinhye.elephantsafe.db.ApplockOpenHelper;

public class ApplockDao {
	private final String TABLE = "applock";
	private ApplockOpenHelper openHelper;
	private Context context;

	public ApplockDao(Context context) {
		openHelper = new ApplockOpenHelper(context);
		this.context = context;
	}
	
	/**
	 * Add a data to applock table.
	 * @param packname The package name you want to add
	 */
	public void add(String packname) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("packname", packname);
		db.insert(TABLE, null, values);
		db.close();
		
		//通知内容观察者，applock数据库变化了！
		Uri uri = Uri.parse("content://com.shinhye.elephantsafe.applockdb");
		context.getContentResolver().notifyChange(uri, null);
	}
	
	/**
	 * Delete a data from applock table.
	 * @param packname The package name you want to add
	 */
	public void delete(String packname) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		db.delete(TABLE, "packname=?", new String[]{packname});
		db.close();
		
		Uri uri = Uri.parse("content://com.shinhye.elephantsafe.applockdb");
		context.getContentResolver().notifyChange(uri, null);
	}
	
	/**
	 * Find the specified package is existed in applock table or not.
	 * @param packname The package name you want to find.
	 * @return If exist return true
	 */
	public boolean find(String packname) {
		SQLiteDatabase db = openHelper.getWritableDatabase();
		Cursor cursor = db.query(TABLE, null, "packname=?", new String[]{packname}, null, null, null);
		boolean isExist = false;
		if(cursor.moveToNext()) {
			isExist = true;
		}
		cursor.close();
		db.close();
		return isExist;
	}
	
	/**
	 * Find all data in the table applock.
	 * @return a list with all package name.
	 */
	public List<String> findAll() {
		List<String> list = new ArrayList<String>();
		SQLiteDatabase db = openHelper.getWritableDatabase();
		
		Cursor cursor = db.query(TABLE, new String[]{"packname"}, null, null, null, null, null);
		while(cursor.moveToNext()) {
			list.add(cursor.getString(0));
		}
		cursor.close();
		db.close();
		return list;
	}
	
}
